package com.zkingsoft.generator;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import com.zkingsoft.actions.common.BaseController;
import com.zkingsoft.codeApi.Configuration;
import com.zkingsoft.plugin.util.DateUtils;

/**
 * 数据库操作类
 * 
 * @author Matrix-J
 */
public class Dbconnection {

	/**
	 * 查询出来数据集
	 */
	public static final String RESULT_LIST_KEY = "LIST";
	/**
	 * 查询出来数据条目
	 */
	public static final String RESULT_LIST_COUNT = "COUNT";

	/**
	 * 关闭连接
	 */
	public void colseConnection(Connection ct, PreparedStatement ps, ResultSet rs) {
		try {
			if (ct != null) {
				ct.close();
			}

			if (rs != null)
				rs.close();
			rs = null;

			if (ps != null)
				ps.close();
			ps = null;
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 更新数据
	 * 
	 * @param sql
	 * @param paras
	 * @return int
	 * @throws SQLException
	 */
	public int update(String sql, String[] paras, Connection ct) throws SQLException {
		PreparedStatement ps = null;
		ResultSet rs = null;
		int answer = 0;
		try {
			ps = ct.prepareStatement(sql);
			if (paras != null) {
				for (int i = 0; i < paras.length; i++) {
					ps.setObject(i + 1, paras[i]);
				}
			}
			answer = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			colseConnection(ct, ps, rs);
		}
		return answer;
	}

	/**
	 * 外部进行数据链接管理操作
	 * 
	 * @param sql
	 * @param paras
	 * @return int
	 * @throws SQLException
	 */
	public int update(Connection ct, String sql, String[] paras) throws SQLException {
		PreparedStatement ps = null;
		ResultSet rs = null;
		int answer = 0;
		try {
			ps = ct.prepareStatement(sql);
			if (paras != null) {
				for (int i = 0; i < paras.length; i++) {
					ps.setObject(i + 1, paras[i]);
				}
			}
			answer = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			colseConnection(null, ps, rs);
		}
		return answer;
	}

	/**
	 * 查询结果集，返回map取用
	 * 
	 * @param sql
	 * @param paras
	 * @return ArrayList
	 * @throws SQLException
	 */
	public static Map<String, Object> select(Connection ct, String sql, String[] paras) throws SQLException {
		PreparedStatement ps = null;
		ResultSet rs = null;
		Map<String, Object> resultMap = new TreeMap<String, Object>();
		List rows = new ArrayList();
		int rowCount = 0;

		try {
			ps = ct.prepareStatement(sql);
			if (paras != null) {
				for (int i = 0; i < paras.length; i++) {
					ps.setString(i + 1, paras[i]);
				}
			}
			rs = ps.executeQuery();
			ResultSetMetaData rm = rs.getMetaData();
			// 获取列数
			int count = rm.getColumnCount();
			// 列名称集合
			List<String> colLabels = new ArrayList();
			for (int i = 0; i < count; i++) {
				String colLabel = rm.getColumnLabel(i + 1);
				colLabels.add(colLabel);
			}
			while (rs.next()) {
				Map row = new HashMap();
				for (String colLabel : colLabels) {
					String colVal = converToString(rs.getObject(colLabel));
					row.put(colLabel, colVal);
				}
				rows.add(row);
				rowCount++;
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
		if (rowCount == 0) {
			return null;
		} else {
			resultMap.put(Dbconnection.RESULT_LIST_KEY, rows);
			resultMap.put(Dbconnection.RESULT_LIST_COUNT, rowCount);
			return resultMap;
		}
	}

	public static String converToString(Object o) {
		String result = "";
		if ((o instanceof Integer))
			result = String.valueOf(o);
		else if ((o instanceof String))
			result = (String) o;
		else if ((o instanceof BigDecimal)) {
			result = o.toString();
		} else if ((o instanceof Timestamp)) {
			result = DateUtils.dateFormatStr(new Date(((Timestamp) o).getTime()), "yyyy-MM-dd HH:mm:ss");
		}
		return result;
	}

	/**
	 * 获取数据库连接
	 * 
	 * @param driver
	 * @param url
	 * @param userName
	 * @param passowrd
	 * @return
	 */
	public static Connection getConnection(Configuration configuration) {
		Connection ct = null;
		try {
			Class.forName(configuration.getDriver());
			ct = DriverManager.getConnection(configuration.getUrl(), configuration.getUserName(), configuration.getPassword());
		} catch (Exception e) {
			BaseController.log.error("*********数据表加载失败********************");
			e.printStackTrace();
		}
		return ct;
	}

}
